//
//  MyCenterViewController.swift
//  weile
//
//  Created by LKM on 16/10/20.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
//import PullToMakeFlight

class MyCenterViewController: BaseViewController {

    
    
    @IBOutlet weak var menu_item1: line_top_bottom_uiview!
    @IBOutlet weak var menu_item2: line_top_bottom_uiview!
    @IBOutlet weak var menu_item3: line_bottom_uiview!
    @IBOutlet weak var menu_item4: line_top_bottom_uiview!
    
    private var data:MyCenterTo?;
    
    //var refresher:PullToMakeFlight!;
    
    @IBOutlet weak var lbl_tips: UILabel!
    @IBOutlet weak var grouplistScrollView: UIScrollView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var contentScrollView: UIScrollView!
    @IBOutlet weak var lastView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        grouplistScrollView.height=50;//?? 加了才能正常显示内容.为什么加了约束 高度会是1000？ 但是不会显示出1000的高度
        
        
//        refresher = PullToMakeFlight()
//        contentScrollView.addPullToRefresh(refresher, action: {
//            self.loadData()
//        })
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_setting_bar"), style: .plain, target: self, action: #selector(goMyInfo))
        self.navigationItem.leftBarButtonItem?.tintColor=R.colors._939393
        
        
        ViewHelp.setOnClickListening(menu_item1, self, #selector(onmenu_item1));
        ViewHelp.setOnClickListening(menu_item2, self, #selector(onmenu_item2));
        ViewHelp.setOnClickListening(menu_item3, self, #selector(onmenu_item3));
        ViewHelp.setOnClickListening(menu_item4, self, #selector(onmenu_item4));
        
    }
    
    func onmenu_item1(){
        ActivityRequest.goMyCollectsViewController(self.navigationController!);
    }
    
    func onmenu_item2(){
        
        ActivityRequest.goContactServiceViewController(self.navigationController!);
    }
    func onmenu_item3(){
        ActivityRequest.goFeedBackViewController(self.navigationController!);
    }
    func onmenu_item4(){
        ActivityRequest.goHelpsViewController(self.navigationController!);
    }
    @IBAction func onLoginOutBtnClick(_ sender: BtnBase) {
//        LKMLog("cddcdcd");
//        ViewHelp.showTipsView(containView: self.view, tips: "sss")
        //利用登录界面来做注销
        ActivityRequest.goLogin()
    }
    
    
    func goMyInfo(){
        ActivityRequest.goMyInfoViewController(self.navigationController!)
    }
    override func viewWillAppear(_ animated: Bool) {
        if ( data == nil){
            loadData()
        }
    }
    func loadData(){
        ViewHelp.showProgressActivity(containView: self.view);
        let ts=Api.getMyCenter(preTaskSerialNumber: nil) { (re:ResponEntity) in
            ViewHelp.hideProgressActivity(containView: self.view);
//            self.contentScrollView.endRefreshing(at: self.refresher.position);
            
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
//            ViewHelp.showAlertTipsDialog(tips: "ok", okRun: nil )
            
            self.data=re.data as? MyCenterTo;
            let count = self.data?.grouplist?.count ??  0;
            let width = self.view.width / CGFloat( min( Double(count) ,3.5));
            let height =  self.grouplistScrollView.height
//            LKMLog("======grouplistScrollView.height \(self.grouplistScrollView.height)")
//            self.grouplistScrollView.con.width = CGFloat(count) * width
            self.grouplistScrollView.contentSize = CGSize(width: CGFloat(count) * width, height:height);
            
            ViewHelp.removeAllSubView(self.grouplistScrollView);
            for index in 0..<count {
                let g = self.data?.grouplist![index];
            
                //选中的
                let button = UIButton()
                button.height = CGFloat(height)
                button.width = width
                button.x = CGFloat(index) * width
                button.tag = index
                button.titleLabel!.font = UIFont.systemFont(ofSize: 14)
                button.setTitle(g?.title, for: UIControlState())
                button.setTitleColor(UIColor.gray, for: UIControlState())
                
                button.setTag(&R.id.tag, g);
                //button.setTitleColor(R.colors.base_color, for: .disabled)
                ViewHelp.setOnClickListening(button, self, #selector(self.grouplistItemClick(_:)))
               
//                 LKMLog("=====data!.usergroup \(String(self.data!.usergroup!))")
//                LKMLog("=====g?.id \(g?.id)")
                if String(self.data!.usergroup!) == g?.id {
                    g!.remark=(g?.remark ?? "" )+("\n\n您的会员到期时间："+(self.data?.mytime ?? ""));
                    button.setTitleColor(R.colors.orange2, for: UIControlState())
                    self.grouplistItemClick(button);
                }
                
                self.grouplistScrollView.addSubview(button)
            }
            
        }
        taskAlls.append(ts);
    }
    ///标签 当前选中的按钮
    var selectedButton = UIButton();
    /// 标签上的按钮点击
    func grouplistItemClick(_ button: UIButton) {
        // 修改按钮状态
        selectedButton.isEnabled = true
        selectedButton.backgroundColor=UIColor.clear
        
        button.isEnabled = false
        selectedButton = button
        
        selectedButton.backgroundColor=R.colors._25000000;

        lbl_tips.setText(str: ( button.getTag(&R.id.tag) as! MyCenterTo_UserGroupTo ).remark );
        
//        //滚动
//        var offset = grouplistScrollView!.contentOffset
//        offset.x = selectedButton.x ;//CGFloat(button.tag) * contentView!.width
//        grouplistScrollView!.setContentOffset(offset, animated: true)
    }

    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    override func viewDidLayoutSubviews() {
        contentView.width=contentScrollView.width;//内容大小跟scrollView的一样
        contentView.height=lastView.y+lastView.height;
        //设置scrollview的大小，宽不变，高根据内容，必须的
        self.contentScrollView.contentSize = CGSize(width:  contentView.width,height:contentView.height);
        
    }
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}



import Foundation
import SwiftyJSON

//lkm
class MyCenterTo: NSObject {
    
    var grouplist: [MyCenterTo_UserGroupTo?]?;//
    var usergroup: Int?;//3
    
    var mytime:String?//会员过期时间
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        self.grouplist = MyCenterTo_UserGroupTo.initToList(json:  dict["grouplist"] )//dict["grouplist"]?.string;//
        self.usergroup = dict["usergroup"]?.int;//3
        self.mytime = dict["mytime"]?.string
        }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json: JSON)->[MyCenterTo?]{
        if let items = json.array {
            var results = [MyCenterTo?]()
            for item in items {
                let result = MyCenterTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [MyCenterTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,MyCenterTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,MyCenterTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = MyCenterTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,MyCenterTo>()
    }
    
    
    
    
}

import Foundation
import SwiftyJSON

//lkm
class MyCenterTo_UserGroupTo: NSObject {
    
    var Times: Int?;//"1"
    var Channels: String?;//","
    var consume: Int?;//"150"
    var discount: Int?;//"90"
    var id: String?;//"1"
    var imgurl: String?;//"/UpLoadFiles/20150109/2015010917414304.jpg"
    var integral: Int?;//"20"
    var islock: Int?;//"0"
    var remark: String?;//"唯乐科技致力于打造全球最专业的O2O集成房屋技术支持平台，通过线上为企业提供上千套即时性的房屋建筑施工方案、材料构成及报价，"
    var title: String?;//"普通用户"
    
    //dict["data"].dictionaryObject  dict是JSON
    init?(jsons: [String: JSON]?) {
        super.init()
        if(jsons == nil){
            return nil
        }
        
        if let dict = jsons{
        
        self.Times = dict["Times"]?.int;//"1"
        self.Channels = dict["Channels"]?.string;//","
        self.consume = dict["consume"]?.int;//"150"
        self.discount = dict["discount"]?.int;//"90"
        self.id = dict["id"]?.string;//"1"
        self.imgurl = dict["imgurl"]?.string;//"/UpLoadFiles/20150109/2015010917414304.jpg"
        self.integral = dict["integral"]?.int;//"20"
        self.islock = dict["islock"]?.int;//"0"
        self.remark = dict["remark"]?.string;//"唯乐科技致力于打造全球最专业的O2O集成房屋技术支持平台，通过线上为企业提供上千套即时性的房屋建筑施工方案、材料构成及报价，"
        self.title = dict["title"]?.string;//"普通用户"
        }
    }
    
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToList(json js: JSON?)->[MyCenterTo_UserGroupTo?]?{
        if(js == nil){
            return nil;
        }
        let json = js!
        if let items = json.array {
            var results = [MyCenterTo_UserGroupTo?]()
            for item in items {
                let result = MyCenterTo_UserGroupTo(jsons: item.dictionary )
                //                if(result != nil){//空还加个屁啊  json为“[]” 时 这是不会为空的。除非直接来了个nil
                //                    results.append(result!)
                //                }
                results.append(result)
            }
            return results;
        }
        return [MyCenterTo_UserGroupTo?]()
    }
    
    //initToList( json:JSON(dict["huxing"] ) )  把JSON过的Any转为JSON
    //一定要是JSON要是 [Any] 的话 会装换失败，最后我还是选用这个JSON
    class func initToMap(json: JSON)->Dictionary<String,MyCenterTo_UserGroupTo>{
        if let items = json.dictionary {
            var results = Dictionary<String,MyCenterTo_UserGroupTo>()//取值的时候本身就是可选类型啊,所以这里不用跟数组一样弄可选类型
            for (key, value)  in items {
                let result = MyCenterTo_UserGroupTo(jsons: value.dictionary )
                results[key] = result
            }
            return results;
        }
        return Dictionary<String,MyCenterTo_UserGroupTo>()
    }
    

    
    
    
}


